package com.qm.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qm.pojo.Cart;
import com.qm.pojo.Order;
import com.qm.pojo.OrderItem;
import com.qm.pojo.User;
import com.qm.service.AlipayService;
import com.qm.service.DubboCartService;
import com.qm.service.DubboOrderService;
import com.qm.vo.QmResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 @author james
 @create 2021-05-01 13:58
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Reference(check =  false)//表示消费者启动时，不需要检查是否有服务的提供者
    private DubboCartService dubboCartService;

    @Reference(check = false)//表示消费者启动时，不需要检查是否有服务的提供者
    private DubboOrderService dubboOrderService;

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private JedisCluster jedisCluster;

    /**
     * 跳转到订单确认页面 http://www.qm.com/order/create.html
     * 业务逻辑: 根据userId,之后查询购物车记录信息.之后在页面中展现购物车数据.
     * 页面取值: ${carts}
     */
    @RequestMapping("/create")
    public String create(HttpServletRequest request, Model model) {
        User user = (User) request.getAttribute("QM_USER");
        Long userId = user.getId();
        List<Cart> cartList = dubboCartService.findCartListByUserId(userId);
        model.addAttribute("carts", cartList);
        return "order-cart";
    }

    /**
     * 1.url:http://www.qm.com/order/submit
     * 2.请求参数：form表单提交
     * 3.返回值：qmResult对象 并且包含orderId数据
     */
    @RequestMapping("/submit")
    @ResponseBody
    public QmResult saveOrder(Order order, HttpServletRequest request) {
        User user = (User) request.getAttribute("QM_USER");
        List<OrderItem> orderItems = order.getOrderItems();
        Long userId = user.getId();
        order.setUserId(userId);
        String orderId = dubboOrderService.saveOrder(order);
        for (OrderItem orderItem : orderItems ) {
            dubboCartService.deleteCart(new Cart().setUserId(userId).setItemId(Long.valueOf(orderItem.getItemId())));
        }
        if (!StringUtils.hasLength(orderId)) {
            return QmResult.fail();
        }
        return QmResult.success(orderId);
    }

    @RequestMapping("/payment")
    public void payMent(String id, Model model, HttpServletResponse response, HttpServletRequest request) {
        try {
            Order order = dubboOrderService.findOrderById(id);
            alipayService.aliPay(response,request,order);
            jedisCluster.setex("QM_ORDERID", 120, id);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/success")
    public String findOrderById( Model model ) {
        if (jedisCluster.exists("QM_ORDERID")) {
            String id = jedisCluster.get("QM_ORDERID");
            Order order = dubboOrderService.findOrderById(id);
            model.addAttribute("order", order);
        }
        return "success";
    }

}
